<template>
  <div class="container">
    <el-dialog :title="handleTitle" :visible.sync="dialogFormVisible" @close='formVisible'>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        size="mini"
      >
        <el-form-item prop="title" label="活动名称" placeholder="请输入文章标题">
          <el-input v-model="form.title"></el-input>
        </el-form-item>

        <el-form-item prop="articleBody" label="文章内容" placeholder="请输入内容">
          <quill-editor
            v-model="form.articleBody"
            @blur="$refs.form.validateField('articleBody')"
          ></quill-editor>
        </el-form-item>

        <el-form-item
          label="视频地址"
          placeholder="请输入视频地址"
        >
          <el-input v-model="form.videoURL"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm">确认</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import { add, update } from '@/api/hmmm/articles.js'
export default {
  name: 'articlesAdd',
  components: {
    quillEditor
  },
  computed: {
    handleTitle () {
      return this.form.id ? '修改文章' : '新增文章'
    }
  },
  data () {
    return {
      dialogFormVisible: false,
      form: {
        title: '',
        articleBody: '',
        videoURL: ''
      },
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 点击确认按钮
    confirm () {
      // 进行校验
      this.$refs.form.validate(async (flag) => {
        if (!flag) return
        // 判断是修改还是添加
        if (this.form.id) {
          // 发起请求
          await update({ id: this.form.id, ...this.form })
          // 关闭弹窗
          this.formVisible()
          // 提示用户
          this.$message.success('修改成功')
        } else {
          // 发送添加请求
          await add(this.form)
          // 关闭弹窗
          this.formVisible()
          // 提示用户
          this.$message.success('添加成功')
        }
        // 通知父组件更新数据
        this.$emit('add')
      })
    },
    // 取消按钮
    cancel () {
      this.formVisible()
    },
    // 关闭弹窗
    formVisible () {
      this.dialogFormVisible = false
      this.form = {
        title: '',
        articleBody: '',
        videoURL: ''
      }
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep .ql-container {
  height: 300px;
}

::v-deep .el-form-item__content{
  text-align: right;
}
</style>
